//解析导出的json数据
let msg = require('../protoBuf/proto_login.json');
let protobufRoot = require('protobufjs').Root;
let root = protobufRoot.fromJSON(msg);
let protoCSCmd = require('../protoBuf/protoCSCmd');

let ParseProtoData = {
    /**
     * 服务端数据
     * @param req 
     * @param code 
     * @param data 
     * @returns 
     */
    scData(req, code, data) {
        let arryUti = this.encode(req, data);
        let arrayBuffer = new ArrayBuffer(4 + arryUti.length);
        let dataView = new DataView(arrayBuffer);
        dataView.setInt32(0, code);
        for (let i = 0; i < arryUti.length; i++) {
            dataView.setUint8(i + 4, arryUti[i]);
        }
        return arrayBuffer;
    },
    /**
     * 客户端数据
     * @param buffer 
     * @returns 
     */
    csData(buffer) {
        // console.log('buffer>>>',buffer);
        let arrayBuffer = new Uint8Array(buffer);
        // console.log('arrayBuffer>>>',arrayBuffer);
        let dataView = new DataView(arrayBuffer.buffer, 0, 4);
        let mid = dataView.getInt32(0);
        console.log('mid>>>', mid);
        let buf = arrayBuffer.subarray(4);
        // console.log('buf>>>',buf);
        let deMessage = null;
        if (protoCSCmd.id[mid]) {
            deMessage = this.decode(protoCSCmd.id[mid], buf);
        } else {
            console.warn('协议号未定义', mid);
        }
        return {
            mid: mid,
            deMessage: deMessage
        };
    },
    /**
     * 序列化
     * @param {*} req 'login.LoginReq'
     * @param {*} infoData infoData = {uid:1}
     * @returns 
     */
    encode: function (req, infoData) {
        let info = root.lookupType(req);
        let infoEncodeMessage = info.encode(info.create(infoData)).finish();
        return infoEncodeMessage;
    },
    /**
     * 反序列化
     * @param {*} infoEncodeMessage 
     * @returns 
     */
    decode: function (req, infoEncodeMessage) {
        let info = root.lookupType(req);
        let infoUnSerialized = info.decode(infoEncodeMessage);
        return infoUnSerialized;
    },
    /**
     * ArrayBuffer转Buffer
     * @param {*} arrayBuffer 
     * @returns 
     */
    toBuffer(arrayBuffer) {
        var buf = Buffer.alloc(arrayBuffer.byteLength);
        var view = new Uint8Array(arrayBuffer);
        for (var i = 0; i < buf.length; ++i) {
            buf[i] = view[i];
        }
        return buf;
    }
}

module.exports = ParseProtoData;